<?php

namespace App\Models;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Model;
use Laravel\Passport\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class Admin extends Model
{
    use HasRoles, HasApiTokens, SoftDeletes;

    /**
     * 权限guard_name
     *
     * @var string
     */
    protected $guard_name = 'api_admin';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'mobile', 'password', 'new_password', 'last_logged_ip', 'state', 'producer', 'remark',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
    ];

    /**
     * @var array 软删除字段
     */
    protected $dates = ['deleted_at'];

    /**
     * 重写passport的登入验证
     *
     * @param $login
     * @return \Illuminate\Database\Eloquent\Model|null|object|static
     */
    public function findForPassport($username)
    {
        return $this->where(function ($query) use ($username) {
            $query->where('name', $username)->orWhere('email', $username);
        })->where('state', 1)->first();
    }

    /**
     * @return array|null|string
     */
    public function showState()
    {
        return 1 === $this->state ? __('message.common.available') : __('message.common.disable');
    }

    /**
     * 是否可用
     *
     * @return bool
     */
    public function isAvailable()
    {
        return 1 === $this->state;
    }

    /**
     * 关联
     */
    public function operationLogs()
    {
        return $this->hasMany('App\Models\OperationLog', 'user_id');
    }
}
